package com.api.shopapi.common;

import com.alibaba.fastjson.JSONObject;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.Constants;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;

/**
 * @author maochuan
 * 单个用户推送
 */
public class PushtoSingle {
    private static String appId = "KamtnQFnTf8y9dIaRQg0s2";
    private static String appKey = "uDsUMXgo8x7R2NUVuQPU93";
    private static String masterSecret = "Is0tKdx46m8S4OjBwDNEC1";

    // 如果需要使用HTTPS，直接修改url即可
    static String host = "https://api.getui.com/apiex.htm";
    // static String host = "http://api.getui.com/apiex.htm";

    public static IPushResult sendMessage(String cid, JSONObject jsonObject){
        // 设置后，根据别名推送，会返回每个cid的推送结果
        System.setProperty(Constants.GEXIN_PUSH_SINGLE_ALIAS_DETAIL, "true");
        IGtPush push = new IGtPush(host, appKey, masterSecret);
        TransmissionTemplate template = getNotificationTemplate(jsonObject);
        SingleMessage message = new SingleMessage();
        message.setOffline(true);
        // 离线有效时间，单位为毫秒
        message.setOfflineExpireTime(24 * 3600 * 1000);
        message.setData(template);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);
        // 厂商通道下发策略
        message.setStrategyJson("{\"default\":4,\"ios\":4,\"st\":4}");
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cid);
        //target.setAlias(Alias);
        IPushResult ret = null;
        try {
            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (ret != null) {
            System.out.println(ret.getResponse().toString());
        } else {
            System.out.println("服务器响应异常");
        }
        return ret;
    }

    public static TransmissionTemplate getNotificationTemplate(JSONObject jsonObject) {
        TransmissionTemplate template = new TransmissionTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionType(1);  // 透传消息接受方式设置，1：立即启动APP，2：客户端收到消息后需要自行处理
        template.setTransmissionContent(String.valueOf(jsonObject));

        //template.setAPNInfo(getAPNPayload()); //详见【推送模板说明】iOS通知样式设置
        return template;
    }
}
